package com.amap.gunfighting;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.hardware.Camera;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.MotionEvent;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

public class Fire extends Activity {
	private SurfaceView preview = null;
	private SurfaceHolder previewHolder = null;
	private Camera camera = null;
	private boolean inPreview = false;
	private boolean cameraConfigured = false;
	TextView textviewAzimuth, textviewPitch, textviewRoll, textviewLatitude,
			textviewLongitude;
	private static SensorManager mySensorManager;
	private boolean sersorrunning;
	double Lon = 0;
	double Lat = 0;
	private LocationManager mlocManager;
	private LocationListener mlocListener = new MyLocationListener();
	private ProgressBar progressBar;
	private Button fireButton1;
	private FireTask fireAsychTask;
	private TextView powerTextView;
	int progress_temp = 0;
	String strUrl = "http://83.251.86.183:8080/ZRTrafficWeb/trafficweb";
	//String strUrl = "http://213.103.200.57:8080/zr/trafficweb";
	URL url = null;
	String velocity = "0";
	String z_acc = "1";
	Integer azimuth = 0;
	Integer roll = 0;
	String[] temp;
	
	@SuppressWarnings("deprecation")
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.fire);
		preview = (SurfaceView) findViewById(R.id.fire);
		previewHolder = preview.getHolder();
		previewHolder.addCallback(surfaceCallback);
		previewHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
		powerTextView = (TextView) findViewById(R.id.powerTextView);
		progressBar = (ProgressBar) findViewById(R.id.progressBar1);
		progressBar.setMax(100);

		fireButton1 = (Button) findViewById(R.id.bFire1);
		fireButton1.setOnTouchListener(new OnTouchListener() {
			public boolean onTouch(View view, MotionEvent event) {
				if (event.getAction() == android.view.MotionEvent.ACTION_DOWN) {
					Log.d("TouchTest", "Touch down");
					fireButton1TouchDown();
				} else if (event.getAction() == android.view.MotionEvent.ACTION_UP) {
					Log.d("TouchTest", "Touch up");
					fireButton1TouchUp();
				}
				return true;
			}
		});

		fireButton1.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				Intent myIntent = new Intent(view.getContext(), Fire.class);
				startActivityForResult(myIntent, 0);
			}
		});
		textviewAzimuth = (TextView) findViewById(R.id.textazimuth);
		textviewPitch = (TextView) findViewById(R.id.textpitch);
		textviewRoll = (TextView) findViewById(R.id.textroll);
		textviewLatitude = (TextView) findViewById(R.id.textlatitude);
		textviewLongitude = (TextView) findViewById(R.id.textlongitude);
		mySensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
		List<Sensor> mySensors = mySensorManager
				.getSensorList(Sensor.TYPE_ORIENTATION);

		if (mySensors.size() > 0) {
			mySensorManager.registerListener(mySensorEventListener,
					mySensors.get(0), SensorManager.SENSOR_DELAY_NORMAL);
			sersorrunning = true;
			Toast.makeText(this, "Calculating Orientation", Toast.LENGTH_LONG)
					.show();
		} else {
			Toast.makeText(this, "Sensor Failure", Toast.LENGTH_LONG).show();
			sersorrunning = false;
			finish();
		}
		mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
				5 * 1000, 10, mlocListener);
	}

	public class MyLocationListener implements LocationListener
	{
		public void onLocationChanged(Location location)
		{	
			int Lat = (int) (location.getLatitude() * 1E6);
			int Lon = (int) (location.getLongitude() * 1E6);
			textviewLatitude.setText(String.valueOf(Lat) + " :Latitude");
			textviewLongitude.setText(String.valueOf(Lon) + " :Longitude");
	  	}

		public void onProviderDisabled(String provider) {
			// TODO Auto-generated method stub
		}

		public void onProviderEnabled(String provider) {
			// TODO Auto-generated method stub
		}

		public void onStatusChanged(String provider, int status, Bundle extras) {
			// TODO Auto-generated method stub
		}

	}

	public void fireButton1TouchDown() {
		Log.i("checkMATE", "down");

		fireAsychTask = new FireTask();
		fireAsychTask.execute((Void) null);
	}

	public void fireButton1TouchUp() {
		Log.i("checkMATE", "up");

		
		MediaPlayer explosion = MediaPlayer.create(Fire.this, R.raw.explosion);
		explosion.start();
		Thread timer = new Thread(){
			public void run(){
				try {
					sleep(3000);
				} catch(InterruptedException e){
					e.printStackTrace();
				}finally{
					 startActivity(new Intent(Fire.this, Map.class));
					 //finish the login activity
					 Fire.this.finish();
				}
			}
		};
		timer.start();
		if (fireAsychTask != null) {
			fireAsychTask.cancel(true);
		}
	}

	@Override
	public void onResume() {
		super.onResume();

		camera = Camera.open();
		startPreview();
	}

	@Override
	public void onPause() {
		if (inPreview) {
			camera.stopPreview();
		}

		camera.release();
		camera = null;
		inPreview = false;

		super.onPause();
	}

	private Camera.Size getBestPreviewSize(int width, int height,
			Camera.Parameters parameters) {
		Camera.Size result = null;

		for (Camera.Size size : parameters.getSupportedPreviewSizes()) {
			if (size.width <= width && size.height <= height) {
				if (result == null) {
					result = size;
				} else {
					int resultArea = result.width * result.height;
					int newArea = size.width * size.height;

					if (newArea > resultArea) {
						result = size;
					}
				}
			}
		}

		return (result);
	}

	private void initPreview(int width, int height) {
		if (camera != null && previewHolder.getSurface() != null) {
			try {
				camera.setPreviewDisplay(previewHolder);
			} catch (Throwable t) {
				Log.e("PreviewDemo-surfaceCallback",
						"Exception in setPreviewDisplay()", t);
				Toast.makeText(Fire.this, t.getMessage(), Toast.LENGTH_LONG)
						.show();
			}

			if (!cameraConfigured) {
				Camera.Parameters parameters = camera.getParameters();
				Camera.Size size = getBestPreviewSize(width, height, parameters);

				if (size != null) {
					parameters.setPreviewSize(size.width, size.height);
					camera.setParameters(parameters);
					cameraConfigured = true;
				}
			}
		}
	}

	private void startPreview() {
		if (cameraConfigured && camera != null) {
			camera.startPreview();
			inPreview = true;
		}
	}

	SurfaceHolder.Callback surfaceCallback = new SurfaceHolder.Callback() {
		public void surfaceCreated(SurfaceHolder holder) {
			// no-op -- wait until surfaceChanged()
		}

		public void surfaceChanged(SurfaceHolder holder, int format, int width,
				int height) {
			initPreview(width, height);
			startPreview();
		}

		public void surfaceDestroyed(SurfaceHolder holder) {
			// no-op
		}
	};
	private SensorEventListener mySensorEventListener = new SensorEventListener() {

		public void onSensorChanged(SensorEvent event) {
			// TODO Auto-generated method stub

			textviewAzimuth.setText("Azimuth: "
					+ Integer.valueOf((int) event.values[0]));
			textviewPitch.setText("Pitch: "
					+ Integer.valueOf((int) event.values[1]));
			textviewRoll.setText("Roll: "
					+ Integer.valueOf((int) event.values[2]));
			roll = Integer.valueOf((int) event.values[2]);
			azimuth = Integer.valueOf((int) event.values[0]);
		}

		public void onAccuracyChanged(Sensor sensor, int accuracy) {
			// TODO Auto-generated method stub

		}
	};

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();

		if (sersorrunning) {
			mySensorManager.unregisterListener(mySensorEventListener);
			if(temp.length == 2)
			{
				Toast.makeText(Fire.this, temp[1]+" is killed.", Toast.LENGTH_LONG).show();
			}
			else if (temp.length == 1)
			{
				Toast.makeText(Fire.this, "No one is killed.", Toast.LENGTH_LONG).show();
			}
		}
	}

	private class FireTask extends AsyncTask<Void, Integer, Integer>
	{
		int progress = 0;
		
		@Override
		protected Integer doInBackground(Void... params)
		{
			while (progress < 100)
			{
				if (!FireTask.this.isCancelled())
				{
					progress += 1;
					publishProgress(progress);
					try {
						Thread.sleep(20);
					} catch (InterruptedException e) {
					}
				}
				else
				{
					break;
				}
			}
			return progress;
		}

		@Override
		protected void onProgressUpdate(Integer... values) {
			progressBar.setProgress(values[0]);
		}

		@Override
		protected void onCancelled()
		{
			fireAsychTask = null;
			Log.i("checkMATE", "result: " + progress);
			powerTextView.setText(progress + "%");
			progress_temp = progress;
			
			Thread t = new Thread()
			{
		        public void run()
		        {
					try
					{         
				 	    url = new URL(strUrl); 
				 	     HttpURLConnection urlConn = (HttpURLConnection) url.openConnection(); 
				 	      
				 	     urlConn.setDoInput(true); 
				 	     urlConn.setDoOutput(true); 
				 	     urlConn.setRequestMethod("POST"); 
				 	     urlConn.setUseCaches(false); 
				 	     urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 
				 	     urlConn.setRequestProperty("Charest", "utf-8"); 
				 	     // to connect to the server side 
				 	     urlConn.connect(); 
				 	      
				 	     DataOutputStream dop = new DataOutputStream(urlConn.getOutputStream()); 
				 	     dop.writeBytes("point=" + URLEncoder.encode("shoot","utf-8")); 
				 	     //it is essential that to add "&" to separate two strings
				 	     dop.writeBytes("&username="+ URLEncoder.encode(Map.username,"utf-8"));
				 	     dop.writeBytes("&lon=" + URLEncoder.encode(Double.toString(Lon),"utf-8")); 
				 	     dop.writeBytes("&lat=" + URLEncoder.encode(Double.toString(Lat),"utf-8"));
				 	     dop.writeBytes("&velocity=" + URLEncoder.encode(Integer.toString(progress_temp),"utf-8"));
				 	     dop.writeBytes("&z_acc="+ URLEncoder.encode(z_acc,"utf-8")); 
				 	     dop.writeBytes("&azimuth" + URLEncoder.encode(Integer.toString(azimuth),"utf-8"));
				 	     dop.writeBytes("&roll=" + URLEncoder.encode(Integer.toString(roll),"utf-8")); 
				 	     dop.flush(); 
				 	     dop.close(); 
				 	    
				 	     DataInputStream dis = new DataInputStream(urlConn.getInputStream()); 
				 	     String shootPassage = dis.readUTF();
				 	     // to disconnect the server side
				 	     urlConn.disconnect();
				 	     
				 	     temp = shootPassage.split(" ");
				 	     /*if(temp.length == 2)
						 {
 			 	    		 Toast.makeText(Fire.this, temp[1]+" is killed.", Toast.LENGTH_LONG).show();
							 //startActivity(new Intent(Fire.this, Map.class));
		    				 //finish the login activity
		    				 //Fire.this.finish();
						 }
				 	     else if (temp.length == 1)
				 	     {
				 	    	 Toast.makeText(Fire.this, "No one is killed.", Toast.LENGTH_LONG).show();
							 //startActivity(new Intent(Fire.this, Map.class));
		    				 //finish the login activity
		    				 //Fire.this.finish();
				 	     }*/
			 	   }
				   //catch (MalformedURLException e)  
				   catch (Exception e)
			 	   { 
			 	     // TODO Auto-generated catch block 
			 	     e.printStackTrace(); 
			 	   }
		        }
			};
		  t.start();
		}

		protected void onPostExecute(Integer result)
		{
			fireAsychTask = null;
			Log.i("checkMATE", "result: " + result);
		}
	}//end of FireTask
}
